<!--
 * @Descripttion: 条码主档
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-11-03 14:00:43
 * @LastEditors: GW
 * @LastEditTime: 2021-11-17 09:11:17
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="big-main-wrapper warehouse-type-wrapper requisition-set-wrapper" style="margin:2px 8px;">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">

                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :span="2">
                            <div class="btns" @click="editDataFun(1)">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="submitRequest">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="editDataFun(2)">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="remove">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <a-col :span="2" v-if="showModel=='order'">
                            <div class="btns" @click="changeView('list')">
                                <a-icon class="btns-icon" type="unordered-list" />
                                <div class="btns-text">列表</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div class="table-wrapper-box" v-show="showModel=='list'">
                <a-table :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }" :columns="columns" :data-source="data" :pagination="false" :scroll="{x:1000,y:384}" bordered />
                <!-- <barcode value="5555523421524123123123123131231231231231" :width="1" :height="30" :fontSize="12">
                    Show this if the rendering fails.
                </barcode> -->
            </div>
            <div class="order-warpper-box" v-show="showModel=='order'">
                <section>
                    <div><span class="audit-status" style="z-index:78" v-show="voucherState==1">已审</span></div>
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <a-row class="order-dynamic-form-wrapper">
                                <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                    <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="条码属性编码" :rules="[{ required: true, message:'',trigger:'input'}]">
                                        <a-input v-model.trim="requestData.code"></a-input>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                    <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="条码属性名称" :rules="[{ required: true, message:'',trigger:'input'}]">
                                        <a-input v-model.trim="requestData.name"></a-input>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                    <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="描述">
                                        <a-input v-model.trim="requestData.remark"></a-input>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                    <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="类型">
                                        <a-select v-model="requestData.type" style="width:236px;">
                                            <a-select-option v-for=" (select,index) in typeSelect" :key="index" :value="select.key">
                                                {{select.label}}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </div>
                        <div class="table-box">
                            <a-table v-if="isRouterAlive" id="process_edit_tb" class="atable-edit" :columns="columnsAdd" :customRow="customClick" :data-source="dataSource" :pagination="false" bordered :scroll="{x:1000,y:384}">
                                <template v-for="item in editColumnArraya" :slot="item" slot-scope="text, record ,index">
                                    <div :key="item">
                                        <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" @change="onCellChange(index, item, $event)" />
                                    </div>
                                </template>
                            </a-table>
                        </div>
                        <div class="footer-box">
                            <a-row class="order-dynamic-form-wrapper">
                                <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                    <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="创建人">
                                        <a-input v-model="requestData.createUserName" :disabled="true" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                    <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="创建时间">
                                        <a-input v-model="requestData.createDate" :disabled="true" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </div>
                    </a-form-model>
                    <div class="edit-mask-route" v-show="editMask">
                        <!-- 遮罩（点击修改关闭遮罩） -->
                    </div>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!--  <li @click="handleCopy()">复制行</li> -->

                </ul>
            </div>
        </div>
    </div>
</template>
<script>

import { mapState } from "vuex";
import editableCell from "./editTable/EditableCell"
import { listAttr, saveAttr, deleteAttr, getAttrObjectDetails } from "@/api/inventory/barcode";
export default {
    components: {
        editableCell,
    },
    data () {
        return {
            showModel: 'list',
            //----------↓样式----------
            fromStyle: { paddingTop: "8px" },
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
            editFalse: {
                borderBottom: '1px solid #ded7d7'
            },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 6
            },
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------
            editMask: false,
            visible: false,
            isRouterAlive: true,
            data: [],
            top: 0,
            left: 0,
            dataSource: [],
            editColumnArraya: ['voucherTypeName', 'voucherFieldName', 'remark'],
            dataSourceNumber: 12,//默认渲染多少行表格数据
            thisClickId: null,
            customClick: (record, index) => {
                return {
                    on: {
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            if (index <= this.dataSource.length) {
                                this.openMenu(e);
                                console.log('右键点击的', index);
                                this.thisClickId = index;
                                // this.thisClickRecord = record;
                            }
                        },
                    }
                }
            },
            typeSelect: [{
                label: '文本',
                key: 1,
            }, {
                label: '数字',
                key: 2,
            }, {
                label: '日期',
                key: 3,
            }, {
                label: '单据编号',
                key: 4,
            }],
            columns: [{
                title: '条形码',
                dataIndex: 'code',
            }, {
                title: '条码规则',
                dataIndex: 'code',
            }, {
                title: '条码类型',
                dataIndex: 'code',
            }, {
                title: '物料编码',
                dataIndex: 'code',
            }, {
                title: '物料名称',
                dataIndex: 'code',
            }, {
                title: '规格型号',
                dataIndex: 'code',
            }, {
                title: '计量单位',
                dataIndex: 'code',
            }, {
                title: '数量',
                dataIndex: 'code',
            }, {
                title: '客户',
                dataIndex: 'code',
            }, {
                title: '供应商',
                dataIndex: 'code',
            }, {
                title: '部门',
                dataIndex: 'code',
            }, {
                title: '条码属性编码',
                dataIndex: 'code',
            }, {
                title: '条码属性编码',
                dataIndex: 'code',
            },
            {
                title: '条码属性名称',
                dataIndex: 'name',
            },
            {
                title: '类型',
                dataIndex: 'type',
                customRender: (text, record, index) => {
                    return text == 1 ? '文本' : text == 2 ? '数字' : text == 3 ? '日期' : text == 4 ? '单据编号' : '';
                }
            },
            {
                title: '备注',
                dataIndex: 'remarks',
            },],
            columnsAdd: [{
                title: '序号',
                dataIndex: 'number',
                width: 40,
                align: 'center',
                customRender: (text, record, index) => {
                    return index + 1;
                }
            }, {
                title: '业务对象',
                dataIndex: 'voucherTypeName',
                scopedSlots: { customRender: 'voucherTypeName' },
            },
            {
                title: '业务对象字段',
                dataIndex: 'voucherFieldName',
                scopedSlots: { customRender: 'voucherFieldName' },

            }, {
                title: '备注',
                dataIndex: 'remark',
                scopedSlots: { customRender: 'remark' },
            }],
            pageSize: -1, // 每页多少条数据
            current: 1, // 当前页
            thisData: [], // 当前选中的数据
            putStorage: [], // 入库
            outbound: [], // 出库
            selectedKeys: [],
            selectedRows: [],
            modalTitle: '',
            requestData: {
                name: null,
                code: null,
                type: null,
                remarks: null,
            },
            html: '',
            messages: '',
            // businessObject: [],
        };
    },
    created () {
        this.getData();
        this.tableInit();
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    methods: {
        tableInit () {
            //初始化表格
            for (let i = 0; i < this.dataSourceNumber; i++) {
                this.dataSource.push({})
            }
            this.reload();
            console.log(this.dataSource)
        },
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        changeView (view) {
            this.showModel = view;
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > _this.dataSourceNumber) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }


                    _this.reload();
                },
                onCancel () { },
            });
        },

        onSelectChange (keys, rows) {
            this.selectedKeys = keys;
            this.selectedRows = rows;
        },
        editDataFun (type) {
            //新增 or 修改
            if (type == 1) {
                this.modalTitle = '新增合同条码属性';
                this.requestData = {
                    name: null,
                    code: null,
                    type: null,
                    remarks: null,
                }
                this.showModel = 'order';
                this.dataSource = [];
                if (this.dataSource.length < this.dataSourceNumber) {
                    for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                        let array = {
                            number: i + 1,
                        };
                        this.dataSource.push(array);
                    }
                }
                this.reload();
            } else {
                if (this.selectedRows.length != 1) {
                    this.$message.warning('请选择一条数据修改');
                    return;
                }
                this.requestData = this.selectedRows[0];
                this.modalTitle = '修改合同条码属性';
                this.showModel = 'order';
                //获取业务对象
                getAttrObjectDetails({ id: this.selectedRows[0].id }).then(res => {
                    if (res.code === 200) {
                        this.dataSource = res.data.barcodeAttributeBos;

                        //补足表格
                        if (this.dataSource.length < this.dataSourceNumber) {
                            for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                                let array = {
                                    number: i + 1,
                                };
                                this.dataSource.push(array);
                            }
                        }
                        this.reload();
                    }
                })
            }
        },
        getData () {
            const { pageSize, current } = this;
            let params = { size: pageSize, current: current };
            listAttr(params).then(res => {
                if (res.code == 200) {
                    if (JSON.stringify(res.data) != '[]') {
                        if (res.data.length > 0) {
                            this.data = res.data.map(r => {
                                return { ...r, key: r.id }
                            })
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        remove () {
            if (this.selectedKeys.length != 1) {
                this.$message.warning("请选择一条数据");
                return;
            }
            let that = this;
            this.$confirm({
                title: `是否确认删除 ${that.selectedRows[0].name}`,
                content: "",
                onOk () {
                    deleteAttr({ id: that.selectedRows[0].id }).then(res => {
                        if (res.code == 200) {
                            that.selectedKeys = [];
                            that.$message.success("删除成功");
                            that.getData();
                        } else {
                            that.$message.warning(res.message);
                        }
                    })
                },
                onCancel () { }
            });
        },
        submitRequest () {
            if (this.requestData.code == null) {
                this.$message.warning('请输入编码');
                return;
            }
            if (this.requestData.code.length != 2) {
                this.$message.warning('请输入两位数编码');
                return;
            }
            if (this.requestData.name == null) {
                this.$message.warning('请输入名称');
                return;
            }
            // if (this.requestData.type == null) {
            //     this.$message.warning('请选择类型');
            //     return;
            // }
            this.requestData.createDate = null;
            this.requestData.updateDate = null;
            let data = this.dataSource.filter(res => res.voucherTypeCode != null)
            console.log(data);
            if (data.length < 1) {
                this.$message.warning('业务对象必须存在数据');
                return;
            }
            this.requestData.barcodeAttributeBos = data;
            saveAttr(this.requestData).then(res => {
                if (res.code == 200) {
                    this.selectedKeys = [];
                    this.$message.success("保存成功");
                    this.showModel = 'list';
                    this.getData();
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        onCellChange (indexTable, dataIndex, value) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value, indexTable);

            this.$set(target, dataIndex, value)
            if (dataIndex == 'voucherTypeCode' || dataIndex == 'voucherTypeName') {
                if (value) {
                    target['voucherTypeCode'] = value.voucherTypeCode;
                    target['voucherTypeName'] = value.voucherTypeName;
                } else {
                    target['voucherTypeCode'] = '';
                    target['voucherTypeName'] = '';
                }
            }

            if (dataIndex == 'voucherField' || dataIndex == 'voucherFieldName') {
                if (value) {
                    target['voucherField'] = value.code;
                    target['voucherFieldId'] = value.id;
                    target['voucherFieldName'] = value.name;
                } else {
                    target['voucherField'] = '';
                    target['voucherFieldId'] = '';
                    target['voucherFieldName'] = '';

                }
            }

            this.$nextTick(() => {
                this.dataSource = dataSource;
                console.log('明细数据：', this.dataSource)
                this.reload();
            })

        },
    },
};
</script>
<style lang="less">
    // @import '~@/style/setting/inventory.less';
    @import '~@/style/purchase/voucher.less';
    .table-wrapper-box {
        height: calc(100% - 45px);
        padding: 10px;
    }
    .order-warpper-box {
        padding: 10px;
        overflow-y: auto;
    }
    .barcode-box {
        .ant-form-item {
            margin-bottom: 0px;
        }
    }
</style>
